import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// 统一设置接口基地址
const request = axios.create({
  baseURL: process.env.VUE_APP_URL
})
// 请求拦截
request.interceptors.request.use(
  config => {
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截
request.interceptors.response.use(
  // 状态码为2开头 200-299之前
  res => {
    if (res.data.success) {
      return res.data
    } else {
      Message.error(res.data.message)
      return Promise.reject(res.data.message)
    }
  },
  // 非状态码非2开头
  err => {
    if (err.response && err.response.status === 401) {
      Message.error(err.response.data.message)
      store.commit('user/logout')
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

export default request
